import mysql.connector
from queue import Queue
import threading


class DataProducer:
    def __init__(self):
        self.queue = Queue()

    def produce_data(self):
        # 产生数据并添加到队列
        for i in range(1, 10):
            data = dict()
            data['strategy_id'] = i
            data['message'] = f"data{i}"
            self.queue.put(data)

        # 添加一个 None 作为结束标志
        self.queue.put(None)


class DatabaseWorker(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        # 创建数据库连接
        conn = mysql.connector.connect(
            host="rm-uf6h021c725h86guaro.mysql.rds.aliyuncs.com:3306",
            user="loncus",
            password="Loncus1234&",
            database="metabase_sub-c_test"
        )
        cursor = conn.cursor()

        # 从队列中取出数据并插入数据库
        while True:
            data = self.queue.get()
            if data is None:
                break
            cursor.execute("INSERT INTO t_strategy_data (strategy_id,message) VALUES (%s)", (data,))

        # 提交更改并关闭连接
        conn.commit()
        conn.close()


# 创建数据生产者和数据库工作线程
producer = DataProducer()
worker = DatabaseWorker(producer.queue)

# 启动数据库工作线程
worker.start()

# 产生数据
producer.produce_data()

# 等待数据库工作线程完成
worker.join()
